//
//  SNWXVoiceTestViewController.m
//  app
//
//  Created by 王少宁 on 15/5/5.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "SNWXVoiceTestViewController.h"
#import "WXVoiceSDK.h"
#import "HZMallSearchResultViewController.h"
#import "HZMallSqlDataManager.h"

#define kTitleLabelFont 17

static NSString * const wantGoods = @"请说出您心仪的商品 :)";
static NSString * const pleaseWait = @"正在识别您的话...";
static NSString * const tryAgain = @"未能识别出您说的话 :(\n请点击话筒重说";

@interface SNWXVoiceTestViewController () <WXVoiceDelegate>
@property (nonatomic, retain) WXVoiceSDK * recognizer;
@property (nonatomic, retain) UIButton * backBtn;
@property (nonatomic, retain) UILabel * textLabel;
@property (nonatomic, retain) UIButton * tryAgainBtn;
@property (nonatomic, retain) UIImageView * btnImageView;
@end

@implementation SNWXVoiceTestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [XCommon hexStringToColor:kColor_m_light_gray_background];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    self.navigationController.navigationBar.hidden = YES;
    
    [self createView];
    [self createWXVoiceRecognizer];
}

- (void)createView
{
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backBtn.frame = CGRectOf([self.view.ufo ox:SCREEN_WIDTH-40 oy:40],
                                  [self.view.ubo ow:20 oh:20]);
    [self.backBtn setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"wxVoiceBack@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [self.backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backBtn];
    
    self.textLabel = [[UILabel alloc] init];
    self.textLabel.textColor = [XCommon hexStringToColor:kColor_m_light_gray_text];
    self.textLabel.font = [UIFont systemFontOfSize:kTitleLabelFont];
    self.textLabel.numberOfLines = 0;
    self.textLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.textLabel];
    
    self.tryAgainBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.tryAgainBtn.frame = CGRectOf([self.view.ufo fx:0.5 ox:-75 fy:1.0 oy:-200],
                                      [self.view.ubo ow:150 oh:150]);
    [self.tryAgainBtn addTarget:self action:@selector(tryAgainBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.tryAgainBtn];
    [self createAnimationBtnPic];
}

- (void)createAnimationBtnPic
{
    [self textLableWithText:wantGoods];
    
    self.tryAgainBtn.userInteractionEnabled = NO;
    [self.tryAgainBtn setBackgroundImage:nil forState:UIControlStateNormal];
    
    self.btnImageView = [[UIImageView alloc] init];
    self.btnImageView.frame = self.tryAgainBtn.bounds;
    
    self.btnImageView.animationImages = [NSArray arrayWithObjects:
                                         [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"wxVoice_microphone_1@2x" ofType:@"png"]],
                                         [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"wxVoice_microphone_2@2x" ofType:@"png"]],
                                         [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"wxVoice_microphone_3@2x" ofType:@"png"]],
                                         [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"wxVoice_microphone_4@2x" ofType:@"png"]],
                                         [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"wxVoice_microphone_5@2x" ofType:@"png"]], nil];
    self.btnImageView.animationDuration = 1.5f;
    self.btnImageView.animationRepeatCount = 0;
    [self.btnImageView startAnimating];
    
    [self.tryAgainBtn addSubview:self.btnImageView];
}

//显示 textLabel 的标题,并且根据标题确定 textLable 的 size.height
- (void)textLableWithText:(NSString *)text
{
    CGFloat height = [XCommon heightForString:text fontSize:kTitleLabelFont andWidth:ScreenWidth];
    self.textLabel.frame = CGRectMake(0, 100, ScreenWidth, height);
    self.textLabel.text = text;
}

- (void)createWXVoiceRecognizer
{
    self.recognizer = [WXVoiceSDK sharedWXVoice];
    //可选设置
    _recognizer.silTime = 0.5f;
    //必选设置
    _recognizer.delegate = self;
    [_recognizer setUserKey:@"29696708e04fe2ad37346a465ded49e3cc4e137d7729925a"];
    [_recognizer startOnce];
}

#pragma mark - WXVoiceDelegate
-(void)voiceInputResultArray:(NSArray *)array
{
    if (array && array.count > 0) {
        WXVoiceResult * result = [array firstObject];
        
        NSString * voiceStr = [self finalVoiceStr:result.text];
        DLog(@"%@",result.text);
        
        if (voiceStr.length == 0) {
            [self createTryAgainBtnPic];
        } else {//识别成功
            NSString * text = [NSString stringWithFormat:@"识别到您的话为:\n%@",voiceStr];
            [self textLableWithText:text];

            [self performSelector:@selector(wxVoiceRecogniseSuccess:) withObject:voiceStr afterDelay:1.0f];
        }
        
    } else {
        [self createTryAgainBtnPic];
    }
}

- (void)createTryAgainBtnPic
{
    [self textLableWithText:tryAgain];
    self.tryAgainBtn.hidden = NO;
    [self.tryAgainBtn setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"wxVoice_microtryAgain@2x" ofType:@"png"]] forState:UIControlStateNormal];
    self.tryAgainBtn.userInteractionEnabled = YES;
}

- (NSString *)finalVoiceStr:(NSString *)voiceStr
{
    if (voiceStr.length == 0) {
        return @"";
    }
    
    NSMutableString * voiceString = [NSMutableString stringWithString:voiceStr];
    [voiceString deleteCharactersInRange:NSMakeRange(voiceString.length-1, 1)];
    return voiceString;
}

//微信语音识别成功之后进行跳转
- (void)wxVoiceRecogniseSuccess:(NSString *)str
{
    HZMallSearchResultViewController * searchResultVC = [[HZMallSearchResultViewController alloc] init];
    searchResultVC.keyword = str;
    
    if (str.length != 0) {
        HZMallSqlDataManager *sqlManager = [HZMallSqlDataManager defaultManager];
        [sqlManager updateMallSearchHistoryCacheWithData:str];
    }

    [self.navigationController pushViewController:searchResultVC animated:YES];
}

-(void)voiceInputMakeError:(NSInteger)errorCode
{
    NSLog(@"出现错误 %ld",(long)errorCode);
    [self.btnImageView stopAnimating];
    [self createTryAgainBtnPic];
}

- (void)voiceInputWaitForResult
{
    NSLog(@"录音完成，等待服务器返回识别结果。此时不会再接受新的语音");
    [self.btnImageView stopAnimating];
    [self textLableWithText:pleaseWait];
    self.tryAgainBtn.hidden = YES;
}

- (void)voiceInputDidCancel
{
    NSLog(@"在手动调用的cancel后，取消完成时回调");
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)backBtnClick
{
    [self.recognizer cancel];
}

- (void)tryAgainBtnClick
{
    [self createAnimationBtnPic];
    [self.recognizer startOnce];
}

- (void)dealloc
{

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
